package is.ru.server;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;

/**
 * Created in IntelliJ IDEA.
 * Students: Jón Geir Sigurbjörnsson, Kristinn Helgi Hilmarsson, Jón Rúnar Arnarsson
 * Class: T-408-STNE, Stýrikerfi og netkerfi, 2011-1
 * Project: Programming assignment 3: HTTP web server
 * Date: 16.3.2011
 * Time: 20:17
 */

public class UDPConnectionHandler
{
    DatagramSocket serverSocket = null;

    public UDPConnectionHandler(int port)
    {
        //Try the connection with the given port
        try
        {
            serverSocket = new DatagramSocket(port);
        } catch (IOException e)
        {
            System.out.println("UDPConnectionHandler IOException");
            e.printStackTrace();
        }
    }

    public void start()
    {
        System.out.println("Starting UDP server on port: " + serverSocket.getLocalPort() + ", address: " + serverSocket.getLocalSocketAddress());
        while (true)
        {
            try
            {
                // Make the buffersize upto 2048
                byte[] receiveData = new byte[2048];
                //Create the DatagramPakcet to receive the data
                DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
                serverSocket.receive(receivePacket);
                // Then we send the info and data to the UDPRequestHandler ( who will handle the request)
                new UDPRequestHandler(serverSocket,new String(receivePacket.getData()),receivePacket.getAddress(),receivePacket.getPort());

            } catch (IOException e)
            {
                System.out.println("UDPConnectionHandler IOException");
                e.printStackTrace();
                break;
            }
        }
    }
}

